﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace TST.SharePointObjects
{
    internal class FeatureDefinitionList : SiteObjectList
    {
        public FeatureDefinitionList(LicensingMode licensingMode, SPSite site, SPWeb web, Guid farmID, SharePointObjectsDatabase database)
            : base(licensingMode, site, web, farmID, database)
        {
        }

        private bool IsCentralAdmin
        {
            get
            {
                bool result = true;
                using (SPSite site = SPAdministrationWebApplication.Local.Sites[0])
                {
                    result = string.Compare(site.Url, SPContext.Current.Web.Url, true) == 0;
                }
                if (!result)
                {
                    throw new Exception(string.Format("The web site at url {0} is not the SharePoint Central Administration site.", SPContext.Current.Web.Url));
                }
                return true;
            }
        }

        protected override void doLoadFromWeb()
        {
            if (IsCentralAdmin)
            {
                foreach (SPFeatureDefinition definition in SPFarm.Local.FeatureDefinitions)
                {
                    SiteObject obj = new SiteObject(definition.Id.ToString("B"), String.Format("{0} ({1})", definition.DisplayName, definition.Scope.ToString()), SiteObjectType.FeatureDefinition);
                    obj.Group = definition.Scope.ToString();
                    Add(obj);
                }
            }
        }

        protected override void doLoadFromWeb(string groupFilter, string nameSearch)
        {
            if (IsCentralAdmin)
            {
                foreach (SPFeatureDefinition definition in SPFarm.Local.FeatureDefinitions)
                {
                    if ((string.IsNullOrEmpty(groupFilter) || string.Compare(definition.Scope.ToString(), groupFilter, true) == 0) &&
                       (string.IsNullOrEmpty(nameSearch) || definition.DisplayName.ToLower().Contains(nameSearch.ToLower())))
                    {
                        SiteObject obj = new SiteObject(definition.Id.ToString("B"), String.Format("{0} ({1})", definition.DisplayName, definition.Scope.ToString()), SiteObjectType.FeatureDefinition);
                        obj.Group = definition.Scope.ToString();
                        Add(obj);
                    }
                }
            }
        }

        public override SiteObjectType SiteObjectType
        {
            get
            {
                return SiteObjectType.FeatureDefinition;
            }
        }

    }
}
